package com.zrwl.poscloud.commons.config.mybatis;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.extension.incrementer.H2KeyGenerator;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zrwl.poscloud.commons.holder.SpringContextHolder;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
//@MapperScan("com.zrwl.poscloud.xo.mapper*")//这个注解，作用相当于下面的@Bean MapperScannerConfigurer，2者配置1份即可
public class MybatisPlusConfig {

    @Value("${spring.datasource.url}")
    private String dbUrl;
    @Value("${mybatis-plus.mapper-locations}")
    private String mapperLocations;
    @Value("${mybatis-plus.global-config.refresh-mapper}")
    private Boolean refreshMapper;
    /**
     * 数据库驱动

    @Value("${spring.datasource.driverClassName}")
    String driverClassName;
     */
    private static final ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();

    /**
     * 相当于顶部的：
     * {@code @MapperScan("com.baomidou.springboot.mapper*")}
     * 这里可以扩展，比如使用配置文件来配置扫描Mapper的路径
     */
    @Bean
    public static MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
        scannerConfigurer.setBasePackage("com.zrwl.poscloud.xo.mapper*");
        return scannerConfigurer;
    }


    @Autowired
    private PaginationInterceptor paginationInterceptor;

    /*
     * 分页插件，自动识别数据库类型
     * 多租户，请参考官网【插件扩展】
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    @Bean
    public H2KeyGenerator getH2KeyGenerator() {
        return new H2KeyGenerator();
    }


    /**
     * 性能分析拦截器，不建议生产使用
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }

    /**
     * mapper.xml 热加载
     *
     * @return
     */
    @Bean
    public MybatisMapperRefresh mybatisMapperRefresh() {
        SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) SpringContextHolder.getBean("MySqlSessionFactory");
        Resource[] resources = new Resource[0];
        try {
            resources = resourceResolver.getResources(mapperLocations);
        } catch (IOException e) {
            e.printStackTrace();
        }
        MybatisMapperRefresh mybatisMapperRefresh = new MybatisMapperRefresh(resources, sqlSessionFactory, 10, 5, refreshMapper);
        return mybatisMapperRefresh;

    }

    /**
     * 会话工厂
     *
     * @param defaultDataSource 数据源
     * @return SqlSessionFactory
     * @throws Exception
     */
    @Bean(name = "MySqlSessionFactory")
    @Primary
    public SqlSessionFactory defaultSqlSessionFactory(@Qualifier("applicationDataSource") DataSource defaultDataSource) throws Exception {
        final MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(defaultDataSource);
        //        关键代码 设置 MyBatis-Plus 分页插件
        Interceptor[] plugins = {paginationInterceptor};
        sessionFactory.setPlugins(plugins);
        System.out.println(refreshMapper);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        MybatisPlusProperties properties = new MybatisPlusProperties();
//        if (driverClassName.contains("oracle")) {
//            properties.getGlobalConfig().getDbConfig().setKeyGenerator(new OracleKeyGenerator());
//            properties.getGlobalConfig().getDbConfig().setIdType(IdType.INPUT);
//        } else {
            properties.getGlobalConfig().getDbConfig().setIdType(IdType.AUTO);
//        }

        //配置填充器
        properties.getGlobalConfig().setMetaObjectHandler(new MetaObjectHandlerConfig());
        sessionFactory.setGlobalConfig(properties.getGlobalConfig());
        return sessionFactory.getObject();
    }

}
